//云开发
const db = wx.cloud.database()
const driver_account = db.collection('driver_account')
const users = db.collection('users')
//实时数据监听
let usersGoods = null
let otherUsersGoods = null
let driverAccount = null
//调用的云函数
let upUserMessage = null
let clearUserAllMessage = null
let getOpenid = null
let goodsFinish = null
//markers点
let driverMarkers = []
let otherUserMarkers = []
let initial = {
  id: 0,
  latitude: 0,
  longitude: 0,
  iconPath: '/image/locating/orange.png',
  width: 200,
  height: 66
}
let myself = initial
//获取用户定位
let locationBoolean = true
Page({
  data: {
    maxBoxShow:true,
    finishShow: false,
    phoneShow: '',
    locatingShow: true,
    modal: false,
    color: '',
    modalTitle: '',
    modalCancel: '',
    modalConfirm: '',
    modalContent: '',
    go: '>',
    inputTextFrom: '',
    inputTextTo: '',
    remind: '',
    red: {
      color: 'red',
      remind: '暂时无司机，请稍后',
      go: '!',
    },
    green: {
      color: 'green',
      remind: '选择位置呼叫小白',
      go: '>',
      modalTitle: '请输入地点',
      modalCancel: '取消',
      modalConfirm: '呼叫',
    },
    orange: {
      color: 'orange',
      remind: '正在等待司机接单',
      go: '···',
      modalTitle: '等待司机接单中...',
      modalCancel: '撤回订单',
      modalConfirm: '继续等待',
      modalContent: '司机可能正在忙碌，请耐心等待',
    },
    blue: {
      color: 'blue',
      remind: '已接单，正在赶来',
      go: '···',
      modalTitle: '司机正在火速赶来...',
      modalContent: '！接单后，多次撤销订单会被禁用哦',
      modalCancel: '订单完成',
      modalConfirm: '继续等待',
    },
    latitude: '',
    longitude: '',
    scale: '17',
    markers: [],
    warnTitle: '温馨提示：下单后请保持在线哦！！',
    openid: ''
  },
  onLoad() {
    let that = this
    //调用云函数获取openid.判断是否是已经登录的司机
    getOpenid = wx.cloud.callFunction({
      name: 'getOpenid',
    }).then(res => {
      console.log('openid', res.result)
      that.setData({
        openid: res.result
      })
      //判断是否是已经登录的司机
      driver_account.where({
        state: true,
        openid: res.result
      }).get().then(res1 => {
        console.log('state为true', res1.data)
        if (res1.data.length !== 0) {
          //跳转到司机页面
          wx.reLaunch({
            url: '/pages/xiaobai/xiaobai?number=' + res1.data[0].number + '&driver_id=' + res1.data[0].driver_id
          })
        }
      })
    })
    //清除相关用户表
    that.clearUserAllMessage()
    //用户进入，第一，判断是否有司机
    that.haveDriver()
    //监听司机位置的变化,显示司机位置
    db.collection('driver_account').where({
      work_state: true
    }).watch({
      onChange(res) {
        console.log('成功监听driver_account', res)
        let list = res.docs
        driverMarkers = []
        for (let i = 0; i < list.length; i++) {
          driverMarkers.push({
            id: -i - 1,
            latitude: list[i].latitude,
            longitude: list[i].longitude,
            iconPath: '/image/icom/driverlo.png',
            width: 36,
            height: 72
          })
        }
        that.data.markers = [myself, ...driverMarkers, ...otherUserMarkers]
        that.setData({
          markers: that.data.markers
        })
      },
      onError(err) {
        console.log('监听失败driver_account', err)
      }
    })
    //监听users表中state=1的已经接单的用户数据变化,显示其它用户呼叫位置
    otherUsersGoods = db.collection('users').where({
      state: 1
    }).watch({
      onChange(res) {
        console.log('监听otherUsersGoods成功', res.docs)
        let list = res.docs
        let index = list.findIndex(item => item.openid === that.data.openid)
        if (index !== -1) {
          list.splice(index, 1)
        }
        otherUserMarkers = []
        for (let i = 0; i < list.length; i++) {
          otherUserMarkers.push({
            id: i + 1,
            latitude: list[i].latitude,
            longitude: list[i].longitude,
            iconPath: '/image/icom/user.png',
            width: 36,
            height: 72
          })
        }
        that.data.markers = [myself, ...driverMarkers, ...otherUserMarkers]
        that.setData({
          markers: that.data.markers
        })
        console.log(that.data.markers)
      },
      onError(err) {
        console.log('监听otherUsersGoods失败', err)
      }
    })
    //地图实例
    that.mapCtx = wx.createMapContext('myMap')
  },
  onShow(){
    console.log('监听页面显示1111111111111111111111')
    let that = this
    //判断用户是否已经授权位置信息
    wx.getSetting({
      success(res) {
        console.log('判断用户是否已经授权位置成功')
        if (res.authSetting['scope.userLocation'] !== true) {
          wx.showModal({
            title: '',
            content: '请授权位置信息',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                wx.openSetting({
                  success: (res) => {
                    console.log('用户修改授权')
                  }
                })
              }
            }
          })
        }
      },
      fail(err) {
        console.log('判断用户是否已经授权位置失败')
      }
    })
    //获取用户的地理坐标
    that.getUserLocation()
  },
  onUnload() {
    this.clearUserAllMessage()
    otherUsersGoods.close()
    driverAccount.close()
  },
  //#############内部调用的函数
  //判断是否有司机在线
  haveDriver() {
    let that = this
    driverAccount = db.collection('driver_account').where({
      work_state: true
    }).watch({
      onChange(res) {
        console.log('查询在线司机成功', res.docs)
        if (res.docs.length === 0) {
          that.setData({
            color: that.data.red.color,
            remind: that.data.red.remind,
            go: that.data.red.go,
          })
        } else {
          that.setData({
            color: that.data.green.color,
            remind: that.data.green.remind,
            go: that.data.green.go,
          })
        }
      },
      onError(err) {
        console.log('查询在线司机失败', err)
      }
    })
  },
  //获取用户位置
  getUserLocation() {
    let that = this
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      highAccuracyExpireTime: 3000,
      success(res) {
        console.log('获取用户当前位置成功', res)
        locationBoolean = true
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          scale: '17',
          maxBoxShow:false
        })
      },
      fail(err) {
        console.log('获取用户当前位置失败', err)
        that.setData({
          maxBoxShow:true
        })
        if (!err.errCode) {
          console.log('请勿频繁点击')
          that.setData({
            latitude: that.data.latitude,
            longitude: that.data.longitude,
            scale: '17',
          })
        } else {
          console.log('请打开手机定位')
          if (locationBoolean) {
            locationBoolean = false
            wx.showModal({
              title: '',
              showCancel: false,
              content: '请开启手机定位',
              success(res) {
                //用户点击确定
                if (res.confirm) {
                  //3s后自动调用一次
                  setTimeout(() => {
                    that.getUserLocation()
                  }, 1000)
                }
              }
            })
          } else {
              //3s后自动调用一次
              setTimeout(() => {
                that.getUserLocation()
              }, 1000)
          }
        }
      }
    })
  },
  //设置当主按钮为红色时执行的函数
  isRed() {
    wx.showToast({
      title: '无法呼叫',
      icon: 'error',
      duration: 1000
    })
  },
  //设置当主按钮为绿色时执行的函数
  isGreen() {
    let that = this
    console.log('用户点击绿色按钮')
    that.setData({
      inputTextFrom: '',
      inputTextTo: '',
      modalTitle: that.data.green.modalTitle,
      modalCancel: that.data.green.modalCancel,
      modalConfirm: that.data.green.modalConfirm,
      modal: true,
      color: 'green'
    })
  },
  cancelGreen() {
    let that = this
    that.setData({
      inputTextFrom: '',
      inputTextTo: '',
    })
  },
  confirmGreen() {
    let that = this
    //判断输入框为空
    if (that.data.inputTextFrom === '' || that.data.inputTextTo === '') {
      wx.showToast({
        title: '请完整输入地点',
        icon: 'none',
        duration: 1000
      })
      return
    }
    //隐藏绿色图标
    that.setData({
      locatingShow: false,
    })
    //开加载框
    wx.showLoading({
      title: '加载中',
    })
    console.log('点击获取地图中心点位置')
    // 获取地图中心点位置
    that.mapCtx.getCenterLocation({
      success(res) {
        console.log('获取成功', res)
        let latitudeCenter = res.latitude
        let longitudeCenter = res.longitude
        //调用云函数upUserMessage()上传用户的信息：上下车地点、经纬度
        upUserMessage = wx.cloud.callFunction({
          name: 'upUserMessage',
          data: {
            latitude: latitudeCenter,
            longitude: longitudeCenter,
            textFrom: that.data.inputTextFrom,
            textTo: that.data.inputTextTo,
          }
        })
        //上传成功后
        upUserMessage.then(res => {
          console.log('调用云函数upUserMessage成功', res)
          // 关闭加载
          wx.hideLoading()
          //显示橙色按钮
          myself = {
            id: 0,
            latitude: latitudeCenter,
            longitude: longitudeCenter,
            iconPath: '/image/locating/orange.png',
            width: 200,
            height: 66
          }
          that.data.markers = [myself, ...driverMarkers, ...otherUserMarkers]
          that.setData({
            color: 'orange',
            markers: that.data.markers,
            modal: false,
            openid: res.result
          })
          console.log(that.data.markers)
        }).then(res => {
          // 监听是司机接单
          usersGoods = db.collection('users').where({
            openid: that.data.openid
          }).watch({
            onChange(res) {
              console.log('监听users成功', res)
              if (res.type !== "init" && res.docChanges[0].doc.state === 1) {
                //显示蓝色按钮
                usersGoods.close()
                that.data.markers.some(item => {
                  if (item.id === 0) {
                    item.iconPath = '/image/locating/blue.png'
                  }
                  return true
                })
                that.setData({
                  color: 'blue',
                  markers: that.data.markers,
                  modal: false,
                  finishShow: true
                })
                usersGoods.close()
                that.watchGoodsFinish()
                console.log(that.data.markers)
              }
            },
            onError(err) {
              console.log('监听users成功', err)
            }
          })
        })
      }
    })
  },
  changeInputTextFrom(e) {
    let that = this
    that.setData({
      inputTextFrom: e.detail.value
    })
    console.log(that.data.inputTextFrom)
  },
  changeinputTextTo(e) {
    let that = this
    that.setData({
      inputTextTo: e.detail.value
    })
    console.log(that.data.inputTextTo)
  },
  //设置当按钮为orange时的函数
  isOrange() {
    let that = this
    console.log('用户点击orange按钮')
    that.setData({
      modalTitle: that.data.orange.modalTitle,
      modalCancel: that.data.orange.modalCancel,
      modalConfirm: that.data.orange.modalConfirm,
      modal: true,
      color: 'orange'
    })
  },
  cancelOrange() {
    let that = this
    //删除掉用户下单表该用户信息，并且去掉图标
    that.clearUserAllMessage()
    usersGoods.close()
    clearUserAllMessage.then(res => {
      let index = that.data.markers.findIndex(item => item.id === 0)
      that.data.markers.splice(index, 1)
      that.setData({
        locatingShow: true,
        color: 'green',
        markers: that.data.markers
      })
    })
  },
  confirmOrange() {
    let that = this
    that.setData({
      modal: false
    })
  },
  //设置当按钮为blue时的函数
  isBlue() {
    let that = this
    console.log('用户点击blue按钮')
    that.setData({
      modalTitle: that.data.blue.modalTitle,
      modalCancel: that.data.blue.modalCancel,
      modalConfirm: that.data.blue.modalConfirm,
      modal: true,
      color: 'blue'
    })
  },
  cancelBlue() {
    let that = this
    wx.showModal({
      title: '小白提醒您：',
      content: '请您在上车后，点击完成订单！！！',
      cancelText:'还没上车',
      confirmText:'完成订单',
      success(res) {
        if (res.confirm) {
          //删除掉用户下单表该用户信息，并且去掉图标
          that.clearUserAllMessage()
          clearUserAllMessage.then(res => {
            myself = initial
            that.data.markers = [myself, ...driverMarkers, ...otherUserMarkers]
            that.setData({
              markers: that.data.markers,
              locatingShow: true,
              color: 'green',
              finishShow: false
            })
            goodsFinish.close()
          })
        }
      }
    })
  },
  confirmBlue() {
    let that = this
    that.setData({
      modal: false
    })
  },
  //调用云函数
  //调用clearUserAllMessage清除掉用户相关的的所有订单
  clearUserAllMessage() {
    //开加载框
    wx.showLoading({
      title: '加载中',
    })
    clearUserAllMessage = wx.cloud.callFunction({
      name: 'clearUserAllMessage',
    }).then(res => {
      console.log('清除成功')
      // 关闭加载
      wx.hideLoading()
    })
  },
  //监听司机确认订单完成
  watchGoodsFinish(){
    let that = this
    goodsFinish = db.collection('users').where({
      openid: that.data.openid
    }).watch({
      onChange(res) {
        if(res.docChanges[0].dataType === 'remove'){
          console.log('司机确认订单完成')
          wx.showModal({
            title: '小白提醒您：',
            content: '司机已经确认完成订单！',
            showCancel:false,
            confirmText:'确认',
            success() {
                //去掉图标
                clearUserAllMessage.then(() => {
                  myself = initial
                  that.data.markers = [myself, ...driverMarkers, ...otherUserMarkers]
                  that.setData({
                    markers: that.data.markers,
                    locatingShow: true,
                    color: 'green',
                    finishShow: false
                  })
                  goodsFinish.close()
                })
            }
          })
        }
      },
      onError(err) {
        console.log('监听users成功', err)
      }
    })
  },
  //############页面操作时执行的函数
  //点击中间主按钮
  onMain() {
    let that = this
    console.log('点击主按钮')
    switch (that.data.color) {
      case that.data.red.color:
        that.isRed()
        break;
      case that.data.green.color:
        that.isGreen()
        break;
    }
  },
  //点击标记点
  bindmarkertap(e) {
    let that = this
    console.log('点击了标记点')
    if (e.detail.markerId === 0) {
      var iconPath = that.data.markers.filter(item => {
        return item.id == 0
      })[0].iconPath
      if (iconPath === '/image/locating/orange.png') {
        that.isOrange()
      } else if (iconPath === '/image/locating/blue.png') {
        that.isBlue()
      }
    }
  },
  //##自定义弹窗
  //点取消按钮
  onCancel() {
    console.log('自定义弹窗，点击取消')
    let that = this
    that.setData({
      modal: false,
    })
    switch (that.data.color) {
      case that.data.green.color:
        that.cancelGreen()
        break;
      case that.data.orange.color:
        that.cancelOrange()
        break;
      case that.data.blue.color:
        that.cancelBlue()
        break;
      default: ''
    }
  },
  //点击确认按钮
  onConfirm() {
    let that = this
    console.log('自定义弹窗，点击确认')
    switch (that.data.color) {
      case 'green':
        that.confirmGreen()
        break;
      case 'orange':
        that.confirmOrange()
        break;
      case 'blue':
        that.confirmBlue()
        break;
    }
  },
  //点击回到用户位置
  onPitch() {
    let that = this
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      highAccuracyExpireTime: 3000,
      success(res) {
        console.log('获取用户当前位置成功', res)
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          scale: '17',
        })
      }
    })
    that.mapCtx.moveToLocation()
  },
  //司机点击登录
  onLogin() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  //点击电话
  onPhone() {
    console.log('点击了电话')
    let that = this
    if (that.data.phoneShow === 'phone-animation-to' || that.data.phoneShow === '') {
      that.setData({
        phoneShow: 'phone-animation-from'
      })
    } else {
      that.setData({
        phoneShow: 'phone-animation-to',
      })
    }

  },
  //点击拨号
  onCall(e) {
    console.log(e.target.dataset.number)
    wx.makePhoneCall({
      phoneNumber: e.target.dataset.number
    })
  },
  //点击设置
  onSet() {
    wx.navigateTo({
      url: '/pages/userSet/userSet'
    })
  },
})